

//  统一异常和返回处理

import 'package:yeyu_net/request/hi_base_request.dart';
import 'core/dio_adapter.dart';
import 'core/hi_error.dart';
import 'core/hi_interceptor.dart';
import 'core/hi_net_adapter.dart';

class YeyuNet {
  YeyuNet._();

  HiErrorInterceptor _hiErrorInterceptor;
  static YeyuNet _instance;

  static YeyuNet getInstance() {
    if (_instance == null) {
      _instance = YeyuNet._();
    }
    return _instance;
  }

  Future fire(HiBaseRequest request) async {
    HiNetResponse response;
    var error;
    try {
      response = await send(request);
    } on HiNetError catch (e) {
      error = e;
      response = e.data;
      printLog(e.message);
    } catch (e) {
      //  其他异常
      error = e;
      printLog(e);
    }

    if (response == null) {
      printLog(error);
    }

    var result = response.data;
    printLog(result);
    var status = response.statusCode;
    var hiError;
    switch (status) {
      case 200:
        return result;
      case 401:
        hiError = NeedLogin();
        break;
      case 403:
        hiError = NeedAuth(result.toString(), data: result);
        break;
      default:
        hiError = HiNetError(status, result.toString(), data: result);
        break;
    }

    if (_hiErrorInterceptor != null) {
      _hiErrorInterceptor(hiError);
    }
    throw hiError;
  }

  Future<HiNetResponse<T>> send<T>(HiBaseRequest request) async {
    printLog('url:${request.url()}');
    HiNetAdapter adapter = DioAdapter();
    return adapter.send(request);
  }

  void setErrorInterceptor(HiErrorInterceptor interceptor) {
    this._hiErrorInterceptor = interceptor;
  } 

  void printLog(log) {
    print('hi_net:' + log.toString());
  }
}
